import type { FieldConfig } from '@/components/TableFilter.vue'
import { getFormFields } from '@/utils/formUtils'
import type { FormFieldConfig } from '@/types/form'
import { useRoleStore } from '@/store/roleStore'

// 表格列配置
export const tableColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用戶名稱',
    dataIndex: 'username',
  },
  {
    title: '用戶電郵',
    dataIndex: 'email',
  },
  {
    title: '角色',
    dataIndex: 'roles',
    align: 'center',
  },
  {
    title: '狀態',
    dataIndex: 'status',
  },
  {
    title: '最近登錄時間',
    dataIndex: 'lastLoginTime',
  },
  {
    title: '最後修改人',
    dataIndex: 'updatedBy',
  },
  {
    title: '最後修改時間',
    dataIndex: 'updatedAt',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]
// 過濾項配置
export const filterFields: FieldConfig[] = [
  {
    name: 'username',
    label: '用戶名',
    type: 'input',
    placeholder: '請輸入用戶名稱',
  },
  {
    name: 'email',
    label: '電郵',
    type: 'input',
    placeholder: '請輸入電郵',
  },
  {
    name: 'status',
    label: '狀態',
    type: 'select',
    options: [
      { value: '', label: '全部' },
      { value: 1, label: '啟用' },
      { value: 0, label: '禁用' },
    ],
  },
]

// 表單字段配置
const FormField: Record<string, FormFieldConfig> = {
  username: {
    label: '用戶名',
    type: 'input',
    placeholder: '請輸入用戶名',
    rules: [{ required: true, message: '請輸入用戶名' }],
  },
  email: {
    label: '電郵',
    type: 'input',
    placeholder: '請輸入電郵',
    rules: [{ required: true, message: '請輸入電郵' }],
  },
  status: {
    label: '狀態',
    type: 'select',
    placeholder: '請選擇狀態',
    rules: [{ required: true, message: '請選擇狀態' }],
    options: [
      { key: 1, label: '啟用' },
      { key: 0, label: '禁用' },
    ],
  },
  password: {
    label: '密碼',
    type: 'password',
    placeholder: '請輸入密碼',
    rules: [{ required: true, message: '請輸入密碼' }],
  },
  roles: {
    label: '角色',
    type: 'select',
    placeholder: '請選擇角色',
    rules: [{ required: true, message: '請選擇角色' }],
    mode: 'multiple',
    options: [],
  },
}

// 創建表單字段
export const getCreteFieldConfig = async (fields?: string[]) => {
  const fieldsConfig = getFormFields(FormField, fields)
  return await setRolesOptions(fieldsConfig)
}

export const getEditFieldConfig = async (fields?: string[]) => {
  fields = fields || ['username', 'email', 'status', 'roles']
  const fieldsConfig = getFormFields(FormField, fields)
  return await setRolesOptions(fieldsConfig)
}

// 實現異步獲取角色選項的函數
async function setRolesOptions(fields: any) {
  if (fields && fields.roles) {
    const roleStore = useRoleStore()
    const roles = await roleStore.fetchRoleOptions()
    fields.roles.options = roles.map((item: any) => ({
      key: item.name,
      label: item.name,
      disabled:item.name=='Doctor'?true:false,
    }))
  }
  return fields
}
